<?php
namespace Member\Controller;
use Org\Yike\Member;
use Org\Yike\Pinyin;
class SetController extends CommonController {
    public function _initialize(){
        parent::_initialize();
        $this->is_login();
    }
    /**角色权限**/
    public function role (){
        $arr = array();
        $count = M("user_cate")->where('status=1')->count();
        $pager = new \Org\Util\Page($count, 15);
        $arr['count'] = $count;
        $arr['page'] = $pager->show();

        $arr['list'] = M ('user_cate')
            ->where ('status=1')
            ->limit ($pager->firstRow.','.$pager->listRows)
            ->select ();
        $this->assign ('list', $arr);
        $this->display ();
    }
    public function add_role (){
        if (IS_POST){
            $data = I ('post.data', '');
            $res = M ('user_cate')->add ($data);
            if ($res){
                $this->success('新增成功', U('Set/role'));
            }else{
                $this->error('新增失败');
            }
        }

        $this->display ();
    }
    public function edit_role (){
        $id = I ('get.id', '');
        if (IS_POST){
            $data = I ('post.data', '');
            $res = M ('user_cate')->save($data);
            if ($res){
                $this->success('编辑成功', U('Set/role'));
            }else{
                $this->error('编辑失败');
            }
        }
        $role = M ('user_cate')->where ('id='.$id)->find ();
        $area = M ('area_cate')->where ('id='.$role['area'])->find ();
        $this->assign ('role', $role);
        $this->assign ('area', $area);
        $this->display ();
    }
    public function del_role (){
        $mod = M ('user_cate');
        $ids = I ('get.id', '');
        if (false !== $mod->delete($ids)){
            $this->success('删除成功', U('Set/role'));
        }else{
            $this->error('删除失败');
        }

    }
    public function allot (){
        if (IS_POST){
            $id = I ('post.roleid', '');
            $auths = implode(',', I ('post.auths', '')).',';
            $res = M ('user_cate')->where ('id='.$id)->setField('auth', $auths);
            if ($res){
                $this->success('设置成功', U('Set/role'));
            }else{
                $this->error('设置失败');
            }
        }
        $id = I('get.id', '');
        $all_auths = M ('member_menu')->where ('status=1')->order ('pmid asc')->select ();
        $role = M ('user_cate')->field ('id,name,auth')->where ('id='.$id)->find ();
        $own_auths = explode(',', trim ($role['auth'], ','));
        foreach ($all_auths as $vo){
            if ($vo['pmid'] == 0){
                $menus[$vo['mid']]['title'] = $vo['title'];
            }else{
                $sele = '';
                if (in_array($vo['mid'], $own_auths)) $sele = 'checked';
                $menus[$vo['pmid']]['sub'][] = array (
                    'id' => $vo['mid'],
                    'title' => $vo['title'],
                    'url' => U ($vo['url']),
                    'checked' => $sele
                );
            }
        }
        $this->assign ('role', $role);
        $this->assign ('auths', $menus);
        $this->display ();
    }

    /**小区**/
    public function estates (){
        $e_model = M ('Estate');
        $list = array ();
        $e_model->field ('yk_estate.id');
        $e_model->join ('yk_area_cate ac ON yk_estate.area_id=ac.id', 'LEFT');
        $e_model->where (array ('yk_estate.status=1'));
        $count = $e_model->count ();
        $pager = new \Org\Util\Page($count, 15);
        $arr['count'] = $count;

        $e_model->field ('yk_estate.*,ac.name');
        $e_model->join ('yk_area_cate ac ON yk_estate.area_id=ac.id', 'LEFT');
        $e_model->where (array ('yk_estate.status=1'));
        $e_model->order('yk_estate.add_time desc');
        $e_model->limit($pager->firstRow.','.$pager->listRows);
        $list['list'] = $e_model->select ();
        $list['page'] = $pager->show();

        $this->assign ('list', $list);
        $this->display ();
    }
    public function add_estate (){
        if(IS_POST){
            $data = I ('post.data');
            $data['add_time'] = time();
            $py = new Pinyin();
            $data['alias']=$py->getAllPY($data['title']); //全部拼音
            $data['short'] = $py->getFirstPY($data['title']);//拼音首字母
            $data = $this->_insertPic($data);
            $res = M ('estate')->add($data);
            if ($res){
                $this->success('新增成功', U('Set/estates'));
            }else{
                $this->error('新增失败');
            }
        }
        $this->display ();
    }
    public function edit_estate (){
        if (IS_POST){
            $data = I ('post.data', '');
            $py = new Pinyin();
            $data['alias']=$py->getAllPY($data['title']); //全部拼音
            $data['short'] = $py->getFirstPY($data['title']);//拼音首字母
            $data = $this->_insertPic($data);
            if (empty ($data['file'])) unset($data['file']);
            if (empty ($data['img'])) unset ($data['img']);
            $res = M ('estate')->save($data);
            if ($res){
                $this->success('编辑成功', U('Set/estates'));
            }else{
                $this->error('编辑失败');
            }
        }
        $id = I ('get.id', '');
        $estate = M ('Estate')->where ('id='.$id)->find ();
        $this->assign ('estate', $estate);
        $this->display ();
    }
    public function del_estate (){
        $mod = M ('estate');
        $ids = I ('get.id', '');
        if (false !== $mod->delete($ids)){
            $this->success('删除成功', U('Set/estates'));
        }else{
            $this->error('删除失败');
        }
    }
    /**数据字典***/
    public function dict (){
        $model = M ('room');
        $arr = array();
        $count = $model->field ('id')->where ('status=1')->count ();
        $pager = new \Org\Util\Page($count, 15);
        $arr['count'] = $count;
        $arr['page'] = $pager->show();

        $model->field ('yk_room.*,e.id,e.title,b.bid,b.build as bname,b.alias as balias,un.unid,un.unit as unname,un.alias as unalias');
        $model->join ('yk_estate e ON yk_room.estate_id=e.id', 'LEFT');
        $model->join ('yk_build b ON yk_room.build=b.bid', 'LEFT');
        $model->join ('yk_unit un ON yk_room.unit=un.unid', 'LEFT');
        $model->where ('yk_room.status=1');
        $model->order ('yk_room.add_time desc');
        $model->limit ($pager->firstRow.','.$pager->listRows);
        $arr['list'] = $model->select();
        $this->assign ('list', $arr);
        $this->display ();
    }
    public function add_dict (){
        if (IS_POST){
            $data = I ('post.data');
            $data['build_name'] = empty ($data['build_name']) ? $data['build']: $data['build_name'];
            $data['unit_name'] = empty ($data['build_name']) ? $data['unit']: $data['unit_name'];
            $data['floor_name'] = empty ($data['build_name']) ? $data['fool']: $data['floor_name'];
            $data['room_name'] = empty ($data['build_name']) ? $data['room']: $data['room_name'];
            $data['add_time'] = date ('Y-m-d H:i:s');
            $data = $this->_insertPic($data);
            $res = M ('dict')->add($data);
            if ($res){
                $this->success('新增成功', U('Set/dict'));
            }else{
                $this->error('新增失败');
            }
        }
        $house_type = M ('used_type')->where ('status=1')->select ();
        $this->assign ('house_type', $house_type);
        $this->display ();
    }
    public function edit_dict (){
        $id = I ('get.id', '');
        $model = M ('room');
        if (IS_POST){
            $data['build'] = $_POST['build'];
            $data['build']['alert_time'] = date ('Y-m-d H:s:i');
            $data['unit'] = $_POST['unit'];
            $data['unit']['alert_time'] = date ('Y-m-d H:s:i');
            $data['room'] = $_POST['room'];
            $data['room']['alert_time'] = date ('Y-m-d H:s:i');
            $unit = $this->_insertPic ($data['unit']);
            $bu_result = M ('build')->save($data['build']);
            $un_result = M ('unit')->save($unit);
            $r_result = M ('room')->save($data['room']);
            $bu_result = $bu_result === 0? true: $bu_result;
            $un_result = $un_result === 0? true: $bu_result;
            $r_result = $r_result === 0? true: $bu_result;

            if ($r_result && $un_result && $bu_result){
                $this->success('编辑成功', U('Set/dict'));
            }else{
                $this->error('编辑失败');
            }
        }
        $model->field ('yk_room.*,e.id,e.title,b.bid,b.build as bname,b.alias as balias,un.unid,un.unit as unname,un.alias as unalias,un.area,un.aspect,ut.id as typeid,ut.type_title as type');
        $model->join ('yk_estate e ON yk_room.estate_id=e.id', 'LEFT');
        $model->join ('yk_build b ON yk_room.build=b.bid', 'LEFT');
        $model->join ('yk_unit un ON yk_room.unit=un.unid', 'LEFT');
        $model->join ('yk_used_type ut ON un.used_type=ut.id', 'LEFT');
        $model->where ('yk_room.rid='.$id);
        $dict = $model->find ();
        $house_type = M ('used_type')->where ('status=1')->select ();
        $this->assign ('house_type', $house_type);
        $this->assign ('dict', $dict);
        $this->display ();
    }
    public function del_dict (){
        $mod = M ('room');
        $ids = I ('get.id', '');
        if (false !== $mod->where ('rid='.$ids)->delete()){
            $this->success('删除成功', U('Set/dict'));
        }else{
            $this->error('删除失败');
        }
    }
    /**区域设置**/
    public function area (){
        $model = M ('area_cate');
        $list = array ();
        $model->field('id');
        $model->where (array ('status=1'));
        $count = $model->count ();
        $pager = new \Org\Util\Page($count, 15);
        $arr['count'] = $count;

        $model->where (array ('status=1'));
        $model->order ('pid desc');
        $model->limit($pager->firstRow.','.$pager->listRows);
        $list['list'] = $model->select ();
        $list['page'] = $pager->show();

        $this->assign ('list', $list);
        $this->display ();
    }
    public function add_area (){
        if (IS_POST){
            $model = D ('AreaCate');
            $data = I ('post.data', '');
            $data = $this->_before_insert($model, $data);
            $res = $model->add($data);
            if ($res){
                $this->success('新增成功', U('Set/area'));
            }else{
                $this->error('新增失败');
            }
        }
        $this->display ();
    }
    public function edit_area (){
        if (IS_POST){
            $data = I ('post.data', '');
            $res = M ('area_cate')->save($data);
            if ($res){
                $this->success('编辑成功', U('Set/area'));
            }else{
                $this->error('编辑失败');
            }
        }
        $id = I ('get.id', '');
        $area = D ('AreaCate')->where ('id='.$id)->find ();
        $this->assign ('area', $area);
        $this->display ();
    }
    public function del_area (){
        $mod = D ('AreaCate');
        $ids = I ('get.id', '');
        if (false !== $mod->delete($ids)){
            $this->rec_delete ($mod, $ids);
            $this->success('删除成功', U('Set/area'));
        }else{
            $this->error('删除失败');
        }
    }
    /**
     * 入库数据整理
     */
    protected function _before_insert($model, $data = '') {
        //生成spid
        $data['spid'] = $model->get_spid($data['pid']);
        //生成分类等级
        $data['level'] = $model->get_level($data['spid']);
        //栏目别名
        if($data['alias']==''){
            $py = new Pinyin();
            if($_POST['aliasRadio']==1){
                $data['alias']=$py->getFirstPY($data['name']);	//首字母拼音
            }else{
                $data['alias']=$py->getAllPY($data['name']); //全部拼音
            }
        }
        return $data;
    }
    //递归删除子区域
    private function rec_delete ($mod, $pid){
        $sub_area = implode(',', $mod->where (array ('pid'=>array ('in', $pid)))->getField ('id',true));
        $mod->where (array ('pid'=>array ('in', $pid)))->delete();
        if (empty ($sub_area)){
            return ;
        } else{
            $this->rec_delete($mod, $sub_area);
        }
    }
    //生成字典三步曲
    public function  dict_first (){
        if (IS_POST){
            $da_post = I ('post.', '');
            $date = date ('Y-m-d H:i:s');
            if (empty ($da_post['build'])) $this->error ('请选择楼栋');
            //判断是否已建字典
            $is_build = M ('build')
                ->where (array ('estate_id'=>$da_post['eid'],'build'=>$da_post['build']))
                ->getField ('bid');
            if (empty ($is_build)){
                //生成楼栋
                $data['build'] = $da_post['build'];
                $data['alias'] = $da_post['alias'];
                $data['height'] = $da_post['heg'];
                $data['estate_id'] = $da_post['eid'];
                $data['add_time'] = date ('Y-m-d H:i:s');
                $res = M ('build')->add ($data);
                //生成单元
                $char = ord ('A')-1;
                $unit = array ();
                for ($i=1; $i<=$da_post['unit']; $i++){
                    $name = $i;
                    if ($da_post['alias_type'] == 2) $name = chr ($char+$i);
                    $unit[] = array (
                        'estate_id' => $da_post['eid'],
                        'build' => $res,
                        'unit' => $i,
                        'alias' => $name,
                        'add_time' => $date
                    );
                }
                $create = M ('unit')->addAll ($unit);
            }else{
                $res = $is_build['id'];
                M ('build')->save(array ('bid'=>$res,'alias'=>$da_post['alias'],'height'=>$da_post['heg'],'alert_time'=>$date));
                //删除存在的间元
                $char = ord ('A')-1;
                $unit = array ();

                for ($i=1; $i<=$da_post['unit']; $i++){
                    $is_unit = M ('unit')->where (array ('build'=>$res,'unit'=>$i))->getField('unid');
                    $name = $i;
                    if ($da_post['alias_type'] == 2) $name = chr ($char+$i);
                    if (empty($is_unit)){
                        $unit[] = array (
                            'estate_id' => $da_post['eid'],
                            'build' => $res,
                            'unit' => $i,
                            'alias' => $name,
                            'add_time' => $date,
                            'alert_time' => $date
                        );
                    }else{
                        M ('unit')->save (array ('unid'=>$is_unit,'alert_time'=>$date,'alias'=>$name));
                    }
                }
                if (empty($unit)){
                    $create = true;
                }else{
                    $create = M ('unit')->addAll ($unit);
                }
            }
            if ($res && $create){
                $this->redirect('Set/dict_third', array('bid'=>$res), 0);
            }else{
                $this->error ('网络出错，请重新设置');
            }

        }
        $estate_id = I ('get.id', '');
        $estate = M ('estate')->field ('id,title,alias,build')->where ('id='.$estate_id)->find ();
        $build = array ();
        $char = ord ('A')-1;
        for ($i = 1; $i <= $estate['build']; $i++){
            $build['num'][] = $i;
            $build['char'][] = chr ($char+$i);
        }

        $this->assign ('estate', $estate);
        $this->assign ('build', $build);
        $this->display ();
    }
    /*public function dict_second (){
        if (IS_POST){
            //公共参数
            $comm['type'] = $_POST['type'];
            if ($comm['type'] == 1){
                $img = $this->upload_('unit_num');
                $data = $_POST['unit_num'];
                foreach ($data as $key=>$item) {
                    if (!empty ($item)){
                        $A = count ($item);
                        $B = count(array_filter($item));
                        if ($A != $B && (($A - $B) != 2)){
                            $this->error ('数据填写全，请重新填写');
                        }
                    }
                    $data[$key]['img'] = $img[$key-1]['data']?$img[$key-1]['data']:'';
                    $data[$key]['build'] = $_POST['bid'];
                    $data[$key]['estate_id'] = $_POST['eid'];
                    $data[$key]['add_time'] = date ('Y-m-d H:i:s');
                }
            }elseif($comm['type'] == 2){
                $img = $this->upload_('unit_char');
                $data = $_POST['unit_char'];
                foreach ($data as $key=>&$item) {
                    $A = count ($item);
                    $B = count(array_filter($item));
                    if ($A != $B && (($A - $B) != 2)){
                        $this->error ('数据填写全，请重新填写');
                    }
                    $item['img'] = $img[$key-1]['data']? $img[$key-1]['data']: '';
                    $item['build'] = $_POST['bid'];
                    $item['estate_id'] = $_POST['eid'];
                    $item['add_time'] = date ('Y-m-d H:i:s');
                }
            }
            foreach ($data as $k=>$vo){
                $map = array ('build'=>$vo['build'],'unit'=>$vo['unit']);
                $exist = M ('unit')->field ('unid')->where ($map)->find ();
                if (!empty ($exist)){
                    unset ($data[$k]);
                }
            }
            $res = M ('unit')->addAll(array_values($data));
            if (empty ($data)){
                $this->redirect('Set/dict_third', array('bid'=>$_POST['bid']), 3, '你所填写的单元已存，将调用原先的数据，如要修改请到数据字典中修改');
            }elseif($res){
                $this->redirect('Set/dict_third', array('bid'=>$_POST['bid']), 0);
            }else{
                $this->error ('网络出错，请重新设置');
            }

        }
        $bid = I ('get.bid', '');
        $build = M ('build')->where ('bid='.$bid)->find ();
        $count = empty ($_GET['unit'])? 1: $_GET['unit'];
        $unit = array ();
        $char = ord ('A')-1;
        for ($i = 1; $i <= $count; $i++){
            $unit['num'][] = $i;
            $unit['char'][] = chr ($char+$i);
        }
        //户型
        $used_type = M ('used_type')->where ('status=1')->select ();

        $this->assign ('build', $build);
        $this->assign ('used_type', $used_type);
        $this->assign ('unit', $unit);
        $this->display ();
    }*/
    public function dict_third (){
        $bid = I ('get.bid', '');
        $units = M ('Unit')
            ->field ('yk_unit.*,yk_build.height')
            ->join('yk_build on yk_unit.build=yk_build.bid','LEFT')
            ->where ('yk_unit.build='.$bid)
            ->order ('unit asc')
            ->select ();
        $this->assign ('units', $units);
        $this->display ();
    }
    public function dict_four (){
        $data = I ('post.data');
        $type = I ('post.type', '');
        $floor = I ('post.floor');
        $build = I ('post.build');
        $estate_id = I ('post.estate_id');
        $doorList = array ();
        $legal = true;
        $msg = '';
        $sql = array ();
        foreach ($data as $k => $da){
            $unid = M ('unit')->where (array ('estate_id'=>$estate_id,'build'=>$build,'unit'=>$k))->getField('unid');
            if ($da[1] < $da[0]){
                $legal = false;
                $msg = '起始值不能小于结束值';
                break;
            }
            $doorList[] = $da[0];
            $doorList[] = $da[1];
            $char = ord ('A')-1;
            //var_dump($build);var_dump($unid);var_dump($k); echo PHP_EOL;
            if (M ('room')->where(array ('estate_id'=>$estate_id,'build'=>$build,'unit'=>$unid))->getField('rid')){
                continue;
            }
            for ($f=1; $f<=$floor; $f++){
                for ($i=intval($da[0]); $i<=intval($da[1]); $i++){
                    $room = str_pad($i,2,"0",STR_PAD_LEFT);
                    if ($type == 2) $room = chr ($char+$i);
                    $sql[] = array (
                        'floor' => $f,
                        'f_alias' => $f,
                        'room' => $i,
                        'alias' => $room,
                        'estate_id' => $estate_id,
                        'build' => $build,
                        'unit' => $unid,
                        'add_time' => date ('Y-m-d H:i:s')
                    );
                }
            }

        }
        if (empty ($sql)) {
            $this->success('字典已存在',U('Set/estates'));
            exit;
        }

        if ($legal){
            $res = M ('room')->addAll($sql);
            if ($res){
                $this->redirect('Set/do_dict', array('bid'=>$build), 0);
            }else{
                $this->error ('写入数据库失败失败');
            }
        }else{
            $this->error ($msg);
        }
    }
    public function do_dict (){
        if (IS_POST){
            $data = I ('post.data');
            $model = M ('room');
            $model->startTrans();
            $img = $this->upload_('img');
            $i = 0;
            $error = array ();
            foreach ($data as $key=>$val){
                $val['img'] = empty ($img[$i]['data'])? '': $img[$i]['data'];
                $val['alter_time'] = date ('Y-m-d H:i:s');
                $where = array ('rid'=>array ('in',trim($key,',')));
                $error[] = $model->where ($where)->save($val);
                $i++;
            }
            if (in_array (false, $error)){
                $model->rollback();
                $this->error('没有什么数据更新');
            }else{
                $model->commit();
                $this->success('更新成功',U ('Set/estates'),1);
            }
        }
        $bid = I ('get.bid');
        $room = M ('room')->where ('build='.$bid)->order ('unit asc')->select ();

        $list = array ();
        foreach ($room as $r) {
            $list[$r['unit']][$r['room']]['num'] = $r['alias'];
            $list[$r['unit']][$r['room']]['rid'] .= $r['rid'].',';
        }
        $list = array_values($list);
        $this->assign ('list',$list);
        $this->display ();
    }
    public function config(){
        $configs = M ('configure')->where ('status=1')->select ();
        $this->assign ('configs', $configs);
        $this->display ();
    }
}